#include "stdafx.h"
#include "writer.h"
#include "config.h"
#include "resource.h"
#include "ui_tagger.h"


void main_thread_callback_tag_writer::callback_run()
{
	// Create Window
	CTaggerDialog * dlg = new CTaggerDialog(m_handles, m_strings);
	dlg->Create(core_api::get_main_window());
	dlg->CenterWindow();
	dlg->ShowWindow(SW_SHOWNORMAL);
}


tag_writter::tag_writter(metadb_handle_list_cref p_handles, const pfc::string_list_const & p_strings, const pfc::list_base_const_t<const metadb_handle *> & p_skipped)
: m_data(p_strings)
{
	pfc::dynamic_assert(p_handles.get_count() == m_data.get_count());
	pfc::array_t<t_size> order;

	order.set_size(p_handles.get_count());
	order_helper::g_fill(order.get_ptr(), order.get_size());
	p_handles.sort_get_permutation_t(pfc::compare_t<metadb_handle_ptr, metadb_handle_ptr>, order.get_ptr());
	m_handles.set_count(order.get_size());
	m_strings.set_count(order.get_size());

	bool want_check_skipped = p_skipped.get_count() > 0;

	for(t_size n = 0; n < order.get_count(); ++n) 
	{
		metadb_handle_ptr ptr = p_handles[order[n]];

		if (want_check_skipped)
		{
			t_size index = p_skipped.find_item(ptr.get_ptr());

			if (index != infinite)
				// Skip this
				continue;
		}

		m_handles.add_item(ptr);
		m_strings.add_item(m_data[order[n]]);
	}
}

bool tag_writter::apply_filter( metadb_handle_ptr p_location,t_filestats p_stats,file_info & p_info )
{
	t_size index;

	if (get_lyrics_grabber_config().skip_tag_present 
		&& p_info.meta_exists(get_lyrics_grabber_config().lyric_filed_name))
			return false;

	if (m_handles.bsearch_t(pfc::compare_t<metadb_handle_ptr,metadb_handle_ptr>,p_location,index))
	{
		// Null string, skip writing
		if (!m_strings[index] || !*m_strings[index])
			return false;
		
		if (get_lyrics_grabber_config().lyric_filed_name.is_empty())
			return false;

		p_info.meta_set(get_lyrics_grabber_config().lyric_filed_name, m_strings[index]);

		return true;
	}

	return false;
}
